﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ElectronicCommerce.Framework.Web.Mvc
{
    public class CustomModelDictionary
    {
        private Dictionary<string, object> _models = new Dictionary<string, object>();

        public CustomModelDictionary ModelDictionary
        {
            get { return this; }
        }

        public void Add(object model)
        {
            if (model != null && model is CustomModelBase)
            {
                string typeName = model.GetType().FullName;
                if (_models.ContainsKey(typeName))
                {
                    _models[typeName] = model;
                }
                else
                {
                    _models.Add(typeName, model);
                }

                Type baseModel = model.GetType().BaseType;
                while (baseModel != null)
                {
                    typeName = baseModel.FullName;
                    if (typeName != typeof(CustomModelBase).FullName)
                    {
                        if (_models.ContainsKey(typeName))
                        {
                            _models[typeName] = model;
                        }
                        else
                        {
                            _models.Add(typeName, model);
                        }
                    }
                    baseModel = baseModel.BaseType;
                }
            }
        }

        public TModel Get<TModel>() where TModel : CustomModelBase
        {
            string typeName = typeof(TModel).FullName;
            TModel model = null;
            if (_models.ContainsKey(typeName))
            {
                model = _models[typeName] as TModel;
            }

            if (model != null)
            {
                return model;
            }

            model = Activator.CreateInstance<TModel>();
            model.EmptyModelInstance = true;
            return model;
        }
    }
}
